package com.ebupt.migu.fineoperationactivitymonitor.banner2.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ebupt.migu.banner2.pojo.Banner2Detail;
import com.ebupt.migu.banner2.pojo.Banner2RedisBean;
import com.ebupt.migu.banner2.pojo.Banner2Rule;
import com.ebupt.migu.fineoperationactivitymonitor.banner2.entity.BannerTwoDetail;
import com.ebupt.migu.fineoperationactivitymonitor.banner2.entity.BannerTwoInfo;
import com.ebupt.migu.fineoperationactivitymonitor.banner2.mapper.BannerTwoDetailMapper;
import com.ebupt.migu.fineoperationactivitymonitor.banner2.mapper.BannerTwoInfoMapper;
import com.ebupt.migu.fineoperationactivitymonitor.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author tz
 */
@Slf4j
@Service
public class DataBean2ToRedis {

    @Resource
    private RedisService redisService;
    @Resource
    private BannerTwoInfoMapper bannerTwoInfoMapper;
    @Resource
    private BannerTwoDetailMapper bannerTwoDetailMapper;

    private String REDIS_KEY = "BANNER2_LIST";

    public void setRedisCache() {

        Banner2RedisBean banner2RedisBean = new Banner2RedisBean();
        List<Banner2Detail> banner2Details = new ArrayList<>();
        //查询进行中的活动
        //获取最新的策略
        BannerTwoInfo bannerTwoInfo = bannerTwoInfoMapper.selectOne(
                new QueryWrapper<BannerTwoInfo>()
                        .lambda()
                        .eq(true, BannerTwoInfo::getExecutionStatus, 3)
                        .orderByAsc(BannerTwoInfo::getPriority)
                        .last("limit 1")
        );
        //初始化banner
        List<BannerTwoDetail> banners = new ArrayList<>();
        if (bannerTwoInfo.getId() != null) {
            //查询当前策略banner
            List<BannerTwoDetail> bannerTwoDetails = bannerTwoDetailMapper.selectList(new QueryWrapper<BannerTwoDetail>()
                    .lambda()
                    .eq(true, BannerTwoDetail::getBannerId, bannerTwoInfo.getId()));
            if (bannerTwoDetails.size() > 0) {
                for (BannerTwoDetail bannerTwoDetail : bannerTwoDetails) {
                    //判断是否是有效banner
                    boolean timeToUse = isTimeToUse(bannerTwoDetail.getStartTime(), bannerTwoDetail.getEndTime());
                    if (timeToUse) {
                        banners.add(bannerTwoDetail);
                    }
                }
            }


            //存在有效banner
            if (!banners.isEmpty()) {
                Set<Object> keys = new HashSet<>();
                Map<String, List<BannerTwoDetail>> BannerTwoDetailMap = banners.stream().collect(Collectors.groupingBy(bannerTwoDetail -> bannerTwoDetail.getBannerId()));
                BannerTwoDetailMap.forEach((s, v) -> {
                    keys.add(s);
                    for (BannerTwoDetail bannerTwoDetail : v) {
                        List<Banner2Rule> rules = new ArrayList<>();
                        Banner2Detail banner2Detail = new Banner2Detail();
                        banner2Detail.setPicture(bannerTwoDetail.getPicture());
                        banner2Detail.setGroupId(bannerTwoDetail.getGroupId());
                        banner2Detail.setTitle(bannerTwoDetail.getTitel());
                        banner2Detail.setShowSeq(bannerTwoDetail.getShowSeq());
                        banner2Detail.setShowContent(bannerTwoDetail.getShowContent());
                        banner2Detail.setSkipAddr(bannerTwoDetail.getSkipAddr());
                        banner2Detail.setRules(rules);
                        if (!bannerTwoDetail.getConsJson().isEmpty()) {
                            ArrayList arrayList = JSONObject.parseObject(bannerTwoDetail.getConsJson(), ArrayList.class);
                            for (Object o : arrayList) {
                                Banner2Rule banner2Rule = new Banner2Rule();
                                HashMap hashMap = JSONObject.parseObject(JSON.toJSONString(o), HashMap.class);
                                banner2Rule.setRuleKey(hashMap.get("deviceSystem").toString());
                                banner2Rule.setRuleValue(hashMap.get("deviceValue").toString());
                                banner2Rule.setOperator(Integer.parseInt(hashMap.get("deviceCondition").toString()));
                                rules.add(banner2Rule);
                            }
                        }

                        banner2Details.add(banner2Detail);
                    }
                });
                banner2RedisBean.setActivityId(bannerTwoInfo.getId());
                banner2RedisBean.setBanner(banner2Details);
                log.info("入库  REDIS_KEY：{} 活动id：{} 内容：{}", keys, bannerTwoInfo.getId(), banner2RedisBean);
                Set<Object> set = redisService.getSet(REDIS_KEY);
                redisService.setSet(REDIS_KEY, keys);
                redisService.set(bannerTwoInfo.getId(), JSON.toJSONString(banner2RedisBean));
                boolean b = set.containsAll(keys);
                if (!b) {
                    set.forEach(o -> {
                        redisService.deleteKeys(o.toString());
                        redisService.setMembersDel(REDIS_KEY, o.toString());
                    });

                }
            }
            //不存在有效banner
            else {
                redisService.deleteKeys(REDIS_KEY);
                redisService.deleteKeys(bannerTwoInfo.getId());
                bannerTwoInfoMapper.update(new UpdateWrapper<BannerTwoInfo>()
                        .lambda()
                        .eq(true, BannerTwoInfo::getId, bannerTwoInfo.getId())
                        .set(BannerTwoInfo::getExecutionStatus, 6)
                );
            }

        }
    }

    /**
     * 判断当前时间是否能用
     *
     * @param startTime
     * @param endTime
     * @return
     */
    private boolean isTimeToUse(Date startTime, Date endTime) {
        DateTime now = DateTime.now();
        return now.after(startTime) && now.before(endTime);
    }

}
